<?php

# LemurCMS by Alec Gorge
#
#     This file contains the PHP functions used throught the CMS.
#
# updated: Jan. 12, 2009
# function delete_directory($dirname) {

class themeInstaller extends functions { 
	public function __construct ($file) {
		$this->path = BASE_URL."themes";
		$this->tempPath = BASE_URL."temp";
		$this->file = $file;
	}
	public function delete_directory($dirname) {
		if (is_dir($dirname))
			$dir_handle = opendir($dirname);
		if (!$dir_handle)
			return false;
		while($file = readdir($dir_handle)) {
			if ($file != "." && $file != "..") {
				if (!is_dir($dirname."/".$file))
					unlink($dirname."/".$file);
				else
					delete_directory($dirname.'/'.$file);          
			}
		}
		closedir($dir_handle);
		rmdir($dirname);
		return true;
	}
	public function formatFileSize($fs) { 
		$bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); 
		// values are always displayed in at least 1 kilobyte: 
		if ($fs <= 999) { 
			$fs = 1; 
		} 
		for ($i = 0; $fs > 999; $i++) { 
			$fs /= 1024; 
		} 
		return ceil($fs).$bytes[$i]; 
	}
	public function findexts () { 
		$filename = $this->file;
		$filename = strtolower($filename);
		$exts = explode(".", $filename);
		$n = count($exts)-1;
		$exts[$n] = ""; 
		$exts = implode($exts, ".");
		$exts = substr($exts, 0, -1);
		return trim($exts); 
	} 
	public function test ($file) {
		$zip = new ZipArchive;
		if ($zip->open($this->tempPath.'/'.$file) === TRUE) {
			$zipx = $this->findexts();
			if(!is_dir($this->tempPath."/".$zipx)) {
				mkdir($this->tempPath."/".$zipx);
			}
		    $zip->extractTo($this->tempPath."/".$zipx.$name);
		    $zip->close();
			if(file_exists($this->tempPath.'/'.$zipx.'/index.tpl')) {
				return true;
			}
			else {
				return $this->message('error', 'Oh no! File missing!', 'There isn\'t a index.tpl file in the root the zip file. This is usally caused by having the theme folder inside the zip file.');
			}
			$this->delete_directory($this->tempPath."/".$zipx);
			unlink($this->tempPath.'/'.$file);
		}
		else {
			echo $this->tempPath.'/'.$file;
		    return false;
		}
	}
	public function install ($file, $title) {
		$zip = new ZipArchive;
		if ($zip->open(BASE_URL.'temp/'.$file.'.zip') === TRUE) {
			if(!is_dir($this->path."/".$file)) {
				mkdir($this->path."/".$file);
			}
		    $zip->extractTo($this->path."/".$file.$name);
		    $zip->close();
			return true;
		}
		else {
		    return false;
		}
	}
}
?>
